from django.shortcuts import render
from django.http import HttpResponse, JsonResponse

from myadmin.models import Types, Goods
from myadmin.views.IndexViews import uploads
# Create your views here.

# 网站后台首页

# 打包函数，获取所有类别
from myadmin.views.TypesViews import GetTypesAll


def GetTypesAllGoods():
    '''
    按照顺序获取所有数据
    把数据库中的分类     排序    完成后发送给前台
    :return:
    '''
    # django中的写法 order_by('title')
    goodslist = Goods.objects.exclude(status=2)
    return goodslist

# 商品列表
# def goodsindex(request):
#     # 拿数据
#     goodslist = Goods.objects.all()
#     # 数据构造字典
#     context = {'goodslist':goodslist}
#     # 加载模板
#     return render(request,'myadmin/goods/index.html',context)
#
# # 商品添加
def goodsadd(request):
    # 从models拿数据
    context =  {'typelist':GetTypesAll()}
    # 渲染模板
    return render(request,'myadmin/goods/add.html',context)
# 商品执行添加
def goodsinsert(request):
    try:
        # 接受数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        # 上传商品图片

        print(data)

        myfile = request.FILES.get('pic',None)
        if not myfile:
            return HttpResponse('<script>alert("图片是必选的");location.href="/myadmin/goods/add"</script>')
        # 执行文件上传
        data['pic'] = uploads(myfile)
        # 处理选择的分类数据(tid 外键必须对应一个对象,不能是一个数值)
        data['tid'] = Types.objects.get(id=data['tid'])
        # 数据的添加
        Goods.objects.create(**data)
        # 跳转到列表页
        return HttpResponse('<script>alert("添加成功");location.href="/myadmin/goods/index/"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="/myadmin/goods/add/"</script>')



def goodsedit(request,goods_edit_id):
    ob1 = Types.objects.all()
    ob = Goods.objects.get(id = goods_edit_id)
    context = {'uinfo':ob,'uinfo1':ob1}



    return render(request,'myadmin/goods/edit.html',context)








def goodsdel(request):
    ob = Goods.objects.get(id=request.GET['id'])
    # 状态改成2  已下架
    ob.status = 2
    ob.save()
    return JsonResponse({'error': 0, 'msg': '删除成功'})










# 分类的列表
def goodsindex(request):
    '''
    10个数据一页,获取前端传送的页码并返回  对应页码的数据(总数据匹配当前页的部分)
    :param request:
    :return:
    '''

    users = GetTypesAllGoods()                     #总对象


    # 数据与搜索匹配
    types = request.GET.get('types', None)
    keywords = request.GET.get('keywords', None)
    print(types,keywords)
    if types:
        # 判断是否有搜索条件
        if types == 'all':
            from django.db.models import Q
            # 从所有类别中选择关键字，因此需要用每个字段去分别匹配    'users'   删选后符合条件的对象
            users = users.filter(
                Q(title__contains=keywords) | Q(price__contains=keywords) | Q(num__contains=keywords))
        else:
            # 通过拼接字符串达到上上行的效果
            data = {types + '__contains': keywords}
            users = users.filter(**data)





    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页对象p,每页10个
    p = Paginator(users, 10)            #删选后的对象进行分组后 符合页码条件的对象
    # 当前页码page,如果不存在则返回1
    page = request.GET.get('page', 1)
    # 当前页面数据
    goodslist = p.page(page)
    # 分配数据
    context = {'goodslist': goodslist}

    # 加载模板
    return render(request, 'myadmin/goods/index.html', context)




def goodsupdate(request):
    return  HttpResponse("updates")





